Update 2011 Dec. 14
1 | replace jpg with JPG using ${i/jpg}JPG |
1 2 3 4 | for i in *.jpg; do j=${i /jpg }JPG echo "$i $j" done |
Description
When you want change file names in the Unix Shell, you can use # and % to match a part of the file name and replace this part with other strings you want.
Principle
- # does the match from the left part of our string variable, and it simply remove the matched part. (minimum matching)
- ## does the match from the left part of our string variable, and it simply remove the matched part. (maximum matching)
- % does the match from the right part of our string variable, and it simply remove the matched part. (minimum matching)
- %% does the match from the right part of our string variable, and it simply remove the matched part. (maximum matching)
1 2 3 | old= "human.fa" new=chimp${old #human} echo $old $new |
the result is
1 | human.fa chimp.fa |
1 2 3 | old="music.mp3" new=${old%mp3}wav echo $old $new |
the result is
1 | music.mp3 music.wav |
with the help of *
You can also use the * to help # and % match variable things. Let's see some examples:
Change extension of a lot files
1 2 3 | for i in *.wav; do echo $i ${i%.*}.mp3; done |
the result is:
1 2 3 | a.wav a.mp3 b.wav b.mp3 c.wav c.mp3 |
1 | for i in *.wav; do mv "$i" "${i%%.wav}.mp3"; done |
Change the first underline to dot
1 | for i in *_*; do echo $i ${i%%_*}.${i#*_}; done |
result:
1 2 3 4 | ha1_r1_fa ha1.r1_fa ha1_r2_fa ha1.r2_fa ha2_r1_fa ha2.r1_fa ha2_r2_fa ha2.r2_fa |
Change the last underline to dot
1 | for i in *_*; do echo $i ${i%_*}.${i##*_}; done |
result:
1 2 3 4 | ha1_r1_fa ha1_r1.fa ha1_r2_fa ha1_r2.fa ha2_r1_fa ha2_r1.fa ha2_r2_fa ha2_r2.fa |
Change file name from upper to lower case
1 | for i in *; do echo $i ` echo $i | tr [:upper:] [:lower:]`; done |
Hide Comments